package com.youease.chris.util {
	import com.youease.chris.easing.Linear;
	import com.youease.chris.event.TickEvent;
	import com.youease.chris.event.TweenEvent;
	
	import flash.events.EventDispatcher;
	
	public class Tween extends EventDispatcher {
		
		Tick.instance.addEventListener(TickEvent.TICK,tickHandler);
		
		private static var tweens:Array = [];
		
		private var target:*;
		
		private var isPause:Boolean;
		private var duration:int;
		/**
		 * 缓动函数
		 */
		public var ease:Function = Linear.easeIn;
		
		private var currentTime:int;
		private var fromValues:Object = new Object();
		private var toValues:Object = new Object();
		
		public function Tween(target:Object,duration:Number,params:Object) {
//			if(Tick.instance) {
//				if(!Tick.instance.isRunning) {
//					Tick.instance.start();
//				}
//			}
			
			this.target = target;
			this.duration = duration*1000;
			
			for(var k:String in params) {
				switch(k) {
					default:
						this.fromValues[k] = target[k];
						this.toValues[k] = params[k];
						break;
				}
			}
			
			tweens.push(this);
		}
		
		private static function tickHandler(evt:TickEvent):void {
			updateAll(evt.interval);
		}
		
		private static function updateAll(interval:int=0):void {
			for (var i:int = tweens.length - 1; i >=0; i--) 
			{
				var tween:Tween = tweens[i] as Tween;
				if (tween)
					tween.update(interval);
			}
		}
		
		private function update(interval:int=0):void {
			
			var k:String;
			
			if(this.isPause) return;
			
			this.currentTime += interval;
			
			if(this.currentTime >= this.duration) {
				for(k in this.toValues) {
					updateValue(k,this.toValues[k]);
				}
			}else {
				for(k in this.toValues) {
					var t:int = this.currentTime;
					var newValue:* = calculateValue(t,k);
					updateValue(k,newValue);
				}
			}
			
			//如果已经结束则执行结束回调函数并删除
			if (this.currentTime >= this.duration)
			{
//				if (this.toValues.hasOwnProperty("motionBlur"))
//					(target as DisplayObject).filters = [];
				
//				if (this.onComplete!=null)
//					this.onComplete();
				
				tweens.splice(tweens.indexOf(this), 1);
				
				this.dispatchEvent(new TweenEvent(TweenEvent.TWEEN_END));
			}
				
			
		}
		
		private function updateValue(k:String,v:*):void {
			switch(k) {
				default:
					this.target[k] = v;
					break;
			}
		}
		
		/**
		 * 计算数值 
		 * @param t	时间毫秒数
		 * @param key	属性名
		 * @return 
		 */
		public function calculateValue(t:int,key:String):*
		{
			var a:* = fromValues[key];
			var b:* = toValues[key];
			
			return ease(t, a, b -  a, duration)
		}
		
	}
}